import { createRouter, createWebHistory } from 'vue-router'

const routes = [
    {
        path: '/',
        name: 'Home',
        component: () => import('@/views/HomeView.vue')
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/auth/LoginView.vue')
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('@/views/auth/RegisterView.vue')
    },
    // 管理员路由
    {
        path: '/admin',
        name: 'AdminDashboard',
        component: () => import('@/views/admin/AdminDashboard.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
    },
    {
        path: '/admin/users',
        name: 'UserManagement',
        component: () => import('@/views/admin/UserManagement.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
    },
    {
        path: '/admin/users/add',
        name: 'UserAdd',
        component: () => import('@/views/admin/UserEdit.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
    },
    {
        path: '/admin/users/edit/:id',
        name: 'UserEdit',
        component: () => import('@/views/admin/UserEdit.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
    },
    {
        path: '/admin/exams',
        name: 'AdminExamManagement',
        component: () => import('@/views/admin/ExamManagement.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
    },
    {
        path: '/admin/questions',
        name: 'AdminQuestionManagement',
        component: () => import('@/views/admin/QuestionManagement.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
    },
    {
        path: '/admin/analytics',
        name: 'AdminAnalytics',
        component: () => import('@/views/admin/Analytics.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
    },
    {
        path: '/admin/settings',
        name: 'AdminSettings',
        component: () => import('@/views/admin/Settings.vue'),
        meta: { requiresAuth: true, requiresAdmin: true }
    },
    // 教师路由
    {
        path: '/teacher',
        name: 'TeacherDashboard',
        component: () => import('@/views/teacher/TeacherDashboard.vue'),
        meta: { requiresAuth: true, requiresTeacher: true }
    },
    {
        path: '/teacher/exams',
        name: 'TeacherExams',
        component: () => import('@/views/teacher/ExamManagement.vue'),
        meta: { requiresAuth: true, requiresTeacher: true }
    },
    {
        path: '/teacher/questions',
        name: 'TeacherQuestions',
        component: () => import('@/views/teacher/QuestionManagement.vue'),
        meta: { requiresAuth: true, requiresTeacher: true }
    },
    {
        path: '/teacher/results',
        name: 'TeacherResults',
        component: () => import('@/views/teacher/ResultManagement.vue'),
        meta: { requiresAuth: true, requiresTeacher: true }
    },
    {
        path: '/teacher/students',
        name: 'TeacherStudents',
        component: () => import('@/views/teacher/StudentManagement.vue'),
        meta: { requiresAuth: true, requiresTeacher: true }
    },
    {
        path: '/teacher/settings',
        name: 'TeacherSettings',
        component: () => import('@/views/teacher/Settings.vue'),
        meta: { requiresAuth: true, requiresTeacher: true }
    },
    // 学生路由（统一布局）
    {
        path: '/student',
        component: () => import('@/views/student/StudentLayout.vue'),
        meta: { requiresAuth: true },
        children: [
            { path: '', name: 'StudentDashboard', component: () => import('@/views/student/StudentDashboard.vue') },
            { path: 'exam-list', name: 'StudentExamList', component: () => import('@/views/student/ExamList.vue') },
            { path: 'history', name: 'StudentHistory', component: () => import('@/views/student/ExamHistory.vue') },
            { path: 'profile', name: 'StudentProfile', component: () => import('@/views/student/Profile.vue') },
            { path: 'settings', name: 'StudentSettings', component: () => import('@/views/student/Settings.vue') },
            { path: 'exam/:id', name: 'StudentExamDetail', component: () => import('@/views/student/ExamView.vue') },
            { path: 'exam/:id/result', name: 'StudentExamResult', component: () => import('@/views/student/ExamResult.vue') }
        ]
    },
    // 通用考试路由
    {
        path: '/exams',
        name: 'ExamView',
        component: () => import('@/views/student/ExamView.vue'),
        meta: { requiresAuth: true }
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('auth_token')
    const userStr = localStorage.getItem('auth_user')
    const user = userStr ? JSON.parse(userStr) : null
    const isAuthenticated = !!token

    console.log('路由守卫 - 目标路径:', to.path)
    console.log('路由守卫 - 认证状态:', isAuthenticated)
    console.log('路由守卫 - 用户信息:', user)
    console.log('路由守卫 - 用户角色:', user?.role)

    // 检查是否需要认证
    if (to.meta.requiresAuth && !isAuthenticated) {
        console.log('需要认证但未登录，重定向到登录页')
        next('/login')
        return
    }

    // 检查角色权限
    if (to.meta.requiresAdmin && user?.role !== 'ADMIN') {
        console.log('需要管理员权限但用户角色不匹配，重定向到首页')
        next('/')
        return
    }

    if (to.meta.requiresTeacher && user?.role !== 'TEACHER') {
        console.log('需要教师权限但用户角色不匹配，重定向到首页')
        next('/')
        return
    }

    console.log('路由守卫通过，继续导航')
    next()
})

export default router
